package com.jpyl.jpMedicalTreatment.util;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

import com.forxindu.kit.box.PreferenceKit;
import com.jpyl.jpMedicalTreatment.common.MedicalSettings;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Utility {

	private Context context;

	public Utility(Context context) {
		this.context = context;
	}

	private static final String RADROM_UUID = "radrom_uuid";

	public static String getClientId(Context context) {
		String clientId = new String();
		String androidId = null;
		String deviceId = null;
		String macAddress = null;
		UUID deviceUUID = null;
		TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (null != telephony) {
			deviceId = telephony.getDeviceId();
		}
		if (null != wifi) {
			WifiInfo wifiInfo = wifi.getConnectionInfo();
			if (null != wifiInfo) {
				macAddress = wifiInfo.getMacAddress();
			}
		}
		androidId = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
		if (null != androidId && null != deviceId && null != macAddress) {
			deviceUUID = new UUID(androidId.hashCode(), ((long) deviceId.hashCode() << 32) | macAddress.hashCode());
		}
		if (null != deviceUUID) {
			clientId = deviceUUID.toString();
		} else {
			if (null == PreferenceKit.getSharedPreference(context, RADROM_UUID, null)
					|| PreferenceKit.getSharedPreference(context, RADROM_UUID, null).equals("")) {
				PreferenceKit.setSharedPreference(context, RADROM_UUID, UUID.randomUUID().toString());
			}
			clientId = PreferenceKit.getSharedPreference(context, RADROM_UUID, null);
		}
		return clientId;
	}

	public static String MD5(String md5) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(md5.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
			}
			return sb.toString().toUpperCase(Locale.getDefault());
		} catch (NoSuchAlgorithmException e) {

		}

		return null;
	}

	public static String getSimpleTimeString(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
		return formatter.format(date);
	}

	public static String getSimpleCurrentTimeString() {
		return getSimpleTimeString(Calendar.getInstance().getTime());
	}

	public static Date tryParse(String s, Date defaultValue) {
		if (s == null)
			return defaultValue;

		Date result = defaultValue;

		try {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());

			result = formatter.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return result;
	}

	public static int tryParse(String s, int defaultValue) {
		if (s == null)
			return defaultValue;

		int result = defaultValue;

		try {
			result = Integer.parseInt(s);
		} catch (NumberFormatException ex) {

		}

		return result;
	}

	public static Date tryParseToDate(String s) {
		try {
			return new Date(Timestamp.valueOf(s).getTime());
		} catch (Exception e) {

		}
		return null;
	}

	public static boolean isTabletDevice(Context context) {
		if (android.os.Build.VERSION.SDK_INT >= 11) { // honeycomb
			// test screen size, use reflection because isLayoutSizeAtLeast is
			// only available since 11
			Configuration con = context.getResources().getConfiguration();
			try {
				Method mIsLayoutSizeAtLeast = con.getClass().getMethod("isLayoutSizeAtLeast", int.class);
				Boolean r = (Boolean) mIsLayoutSizeAtLeast.invoke(con, 0x00000004); // Configuration.SCREENLAYOUT_SIZE_XLARGE
				System.err.println("pad");
				return r;
			} catch (Exception x) {
				x.printStackTrace();
				System.err.println("not pad");
				return false;
			}
		}
		System.err.println("not pad");
		return false;
	}

	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	@SuppressWarnings("deprecation")
	public int getScaleValue(int originalValue) {
		int value = 0;
		BigDecimal sacle = new BigDecimal(originalValue);
		BigDecimal sacleChange = null;
		switch (((Activity) context).getWindowManager().getDefaultDisplay().getWidth()) {
		case 320:
			sacleChange = new BigDecimal(MedicalSettings.MDPI_SCALE_CHANGE);
			break;
		case 480:
			sacleChange = new BigDecimal(MedicalSettings.HDPI_SCALE_CHANGE);
			break;
		case 640:
			sacleChange = new BigDecimal(MedicalSettings.HDPI_SCALE_CHANGE);
			break;
		case 720:
			sacleChange = new BigDecimal(MedicalSettings.XHDPI_SCALE_CHANGE);
			break;
		case 1080:
			sacleChange = new BigDecimal(MedicalSettings.XXHDPI_SCALE_CHANGE);
			break;
		default:
			sacleChange = new BigDecimal(((Activity) context).getWindowManager().getDefaultDisplay().getWidth() / 320);
		}
		sacle = sacle.multiply(sacleChange).setScale(0, BigDecimal.ROUND_DOWN);
		value = sacle.intValue();
		return value;
	}

	public static String getCurrencySymbol(Context context, String currencyCode) {
		String currencySymbol = null;
		currencyCode = currencyCode.toUpperCase(Locale.getDefault());
		Currency currency = Currency.getInstance(currencyCode);
		Locale locale = context.getResources().getConfiguration().locale;
		try {
			currencySymbol = currency.getSymbol(locale);
		} catch (IllegalArgumentException e) {
			currencySymbol = "";
		}
		return currencySymbol;
	}

	public static String intToBigDecimalToString(int number) {
		BigDecimal decimal = new BigDecimal(number);
		return "" + decimal.setScale(0, BigDecimal.ROUND_UP).intValue();
	}

	public static int StringToBigDecimalToInt(String number) {
		if (number == null || number.trim().equals("")) {
			return 0;
		}
		BigDecimal decimal = new BigDecimal(number);
		return decimal.intValue();
	}
}
